import React, { Component } from "react";
import { DatePicker, Input, Table, Badge } from "antd";
import { connect } from "dva";
import moment from "moment";

import tableFilter from "../../../components/tableFilter";
import styles from "./MyMessage.less";
import { getChannelText } from "../../channelType";

const { Search } = Input;
const { RangePicker } = DatePicker;

@connect(stores => ({
  messageData: stores.messageList,
  channelDictionaryModel: stores.channelDictionaryModel,
}))
@tableFilter
class MyMessage extends Component {
  state = {
    pushChannelTypeIds: [],
    readStates: [],
    msgSourceName: "",
    timeAscOrDesc: "desc",
    timeBegin: "",
    timeEnd: "",
    pageNum: 1,
    pageSize: 10,
    pushChannelName: "", // 渠道名称
    messageData: [],
    listTotal: 0,
    loading: false
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.filterFun();
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {}
    });
  }

  renderState = (status, text) => {
    if (status === 1) {
      return <Badge status="success" text={text} />;
    }

    return <Badge status="default" text={text} />;
  };

  renderType = text => {
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    return <span>{getChannelText(channelsTypesData, text)}</span>;
  }

  dateChange = e => {
    if (e && e.length > 0) {
      this.setState(
        {
          timeBegin: e[0].format("YYYY-MM-DD"),
          timeEnd: e[1].format("YYYY-MM-DD 23:59:59"),
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          timeBegin: "",
          timeEnd: "",
          pageNum: 1
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { readStates, pushChannelTypeIds } = this.state;
    this.setState(
      {
        pageNum:
          (filters.stateRead && filters.stateRead !== readStates) ||
            (filters.pushChannelTypeId &&
              filters.pushChannelTypeId !== pushChannelTypeIds)
            ? 1
            : current,
        pageSize,
        timeAscOrDesc:
          sorter.order && sorter.order === "ascend" ? "asc" : "desc",

        readStates: filters.stateRead ? filters.stateRead : [],
        pushChannelTypeIds: filters.pushChannelTypeId
          ? filters.pushChannelTypeId
          : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        msgSourceName: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  pushChannelHandleSearch = e => {
    this.setState(
      {
        pushChannelName: e,
        pageNum: 1
      },
      () => {
        this.filterFun();
      }
    );
  };

  handleSourceNameChange = e => {
    this.setState({
      msgSourceName: e.target.value
    });
  };

  handleChannelNameChange = e => {
    this.setState({
      pushChannelName: e.target.value
    });
  };

  filterFun = () => {
    const {
      pushChannelTypeIds,
      readStates,
      msgSourceName,
      timeAscOrDesc,
      timeBegin,
      timeEnd,
      pageNum,
      pageSize,
      pushChannelName
    } = this.state;
    const { dispatch } = this.props;
    const temp = {
      pushChannelTypeIds,
      readStates,
      msgSourceName,
      timeAscOrDesc,
      timeBegin,
      timeEnd,
      pageNum,
      pageSize,
      pushChannelName
    };
    this.setState({
      loading: true
    });
    dispatch({
      type: "messageList/myMessage",
      payload: {
        pageNum: String(pageNum),
        pageSize: String(pageSize),
        ...temp
      }
    }).then((res = {}) => {
      const { datas = [], totalCount = 0 } = res;
      this.setState({
        messageData: datas.map((item, index) => ({
          ...item,
          rowKey: index
        })),
        listTotal: totalCount,
        loading: false
      });
    });
  };

  render() {
    const {
      pageNum,
      messageData = [],
      listTotal,
      pageSize,
      loading
    } = this.state;
    const { channelDictionaryModel } = this.props;
    const { CHANNEL_VALUE = [] } = channelDictionaryModel;
    const columns = [
      {
        title: "消息源名称",
        dataIndex: "msgSourceName",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "渠道类型",
        dataIndex: "pushChannelTypeId",
        render: text => (text ? this.renderType(text) : "--"),
        filters: CHANNEL_VALUE,
        filterMultiple: false
      },

      {
        title: "渠道名称",
        dataIndex: "pushChannelName"
      },

      {
        title: "分发时间",
        dataIndex: "timeCreate",
        sorter: true,
        defaultSortOrder: "descend",
        render: (text, record) =>
          moment(record.timeCreate).format("YYYY-MM-DD HH:mm:ss")
      },
      // {
      //   title: "状态",
      //   dataIndex: "stateRead",
      //   filters: [{ text: "未读", value: 0 }, { text: "已读", value: 1 }],
      //   filterMultiple: false,
      //   render: (text, record) =>
      //     `${text}` !== ""
      //       ? this.renderState(record.stateRead, record.stateReadName)
      //       : "--"
      // },

      {
        title: "消息来源",
        dataIndex: "msgSourceType"
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>我的消息</div>
        <div style={{ padding: '20px' }}>
          <div className={styles.topSearch}>
            分发时间：

            <RangePicker
              showTime
              style={{ width: 224, marginLeft: 8, marginRight: 24 }}
              onChange={this.dateChange}
            />
            <Search
              placeholder="消息源名称"
              style={{ width: 272, marginRight: 24 }}
              onChange={this.handleSourceNameChange}
              onSearch={this.handleSearch}
              allowClear
            />
            <Search
              placeholder="渠道名称"
              style={{ width: 272 }}
              onChange={this.handleChannelNameChange}
              onSearch={this.pushChannelHandleSearch}
              allowClear
            />
          </div>
          <Table
            style={{ background: '#fff' }}
            columns={columns}
            size="middle"
            dataSource={messageData}
            loading={loading}
            locale={{ emptyText: "暂无数据！" }}
            scroll={messageData.length === 0 ? { x: false } : { x: 1200 }}
            rowKey={(record) => `${record.rowKey}`}
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            pagination={{
              defaultPageSize: pageSize,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageNum,
              total: listTotal,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
      </div>
    );
  }
}

export default MyMessage;
